package com.eagle.security.controller;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.eagle.security.dao.PermissionDao;
import com.eagle.security.entries.Permission;
import com.eagle.security.entries.RoleGroup;
import com.eagle.security.entries.User;
import com.eagle.security.entries.UserCopy;
import com.eagle.security.entries.ui.ETree;
import com.eagle.security.service.RoleGroupManageService;
import com.eagle.security.service.UserManageService;

@RequestMapping("/sysmanage")
@Controller
public class SysManageController {

    @Resource
    private UserManageService userManage ; 
    
    @Resource
    private RoleGroupManageService roleGroupManage;
    
    @Resource
    private PermissionDao permissionDao ;
    
    @RequestMapping(value = { "/index" }   )
    public String loadWidgetData( ModelMap model) {
        try {
            model.put("user", "xugang");
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        return "/sysmanage/index_1";
    }
    
    //-------------------------------------------------------------------用户管理----------------------------------------------------------------------------------------
    /**
     * 获取用户管理列表
     * @return
     */
    @RequestMapping(value = { "/user/userlist" }   )
    public String userlist( HttpServletRequest request, ModelMap model) {
    	String pjax = request.getHeader("X-PJAX") ;
    	
    	Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    	if( principal instanceof User ){
    		User u =(User)principal;
    		System.out.println( u.getAuthorities().size() );
    	}
    	
    	if( StringUtils.isBlank(pjax)){
    		return "/sysmanage/user/user_index_whole";
    	}
        return "/sysmanage/user/user_index";
    }
    
    /**
     * 返回用户列表json数据， 支持easyui datagrid控件
     * @param model
     * @return
     */
    @ResponseBody
    @RequestMapping(value = { "/user/user_datagrid/json" }   )
    public Map<String,Object> userIndex( 
    		@RequestParam(value="page",required=false) int page, 
            @RequestParam(value="pageSize",required=false) int pageSize,
            @RequestParam(value="keyword",required=false) String keyword,
            ModelMap model) {
        Map<String,Object> datagridMap = new HashMap<String,Object>();
        try {
            User mo = new User();
            mo.setKeyword(keyword);
            List<Map<String,Object>> list = userManage.findUserMapsByCond(mo, page, pageSize);
            int count = userManage.findUserCountByCond(mo);
            datagridMap.put("total", count);
            datagridMap.put("rows", list);
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        return datagridMap;
    }
    
    /**
     * 打开用户修改页面
     * @param username
     * @param model
     * @return
     */
    @RequestMapping( value={"/user/user_pre_save"} )
    public String prepareSaveUser( @RequestParam(value="username") String username, ModelMap model  ){
    	if( StringUtils.isBlank( username )){
    		return "/sysmanage/user/template/user_add";
    	}
        model.put("data", userManage.findUserMapByUsername( username ) );
        return "/sysmanage/user/template/user_edit";
    }

    /**
     * 修改用户信息
     * @param username
     * @param model
     * @return
     * @throws NoSuchMethodException 
     * @throws InvocationTargetException 
     * @throws IllegalAccessException 
     */
    @RequestMapping( value={"/user/user_save"} )
    @ResponseBody
    public Map<String,Object> saveUser( 
    		@RequestParam(value="username") String username, 
    		@RequestParam(value="truename") String truename,
    		@RequestParam(value="nickname") String nickname,
    		@RequestParam(value="isenable") boolean isenable,
    		@RequestParam(value="password") String password,
    		@RequestParam(value="isnew") String isnew,
    		ModelMap model  ) throws Exception{
    	try {
    		if( isnew.equals("true") ){	//新增
    			User user = new User(username, password, nickname, isenable);
    			user.setTruename(truename);
    			model.put("res", userManage.saveUser(user));
    		}
    		else{	//修改
	        	UserCopy mo = new UserCopy();
	        	mo.setUsername(username);
	        	mo.setTruename(truename);
	        	mo.setNickname(nickname);
	        	mo.setEnable(isenable);
	        	model.put("res",userManage.modifyUser(mo) );
    		}
		}catch( AccessDeniedException ade ){
			model.put("res", -1 );
		}catch (Exception e) {
			e.printStackTrace();
		}
        return model ;
    }
    
    
    /**
     * 打开分配角色页面
     * @param username
     * @return
     */
    @RequestMapping( value={"/user/user_pre_assignRole"} )
    public String prepareAssignUser( 
    		@RequestParam(value="username") String username, 
    		@RequestParam(value="index") String index,  
    		ModelMap model  ){
        try {
	    	model.put("index", index);
	    	Map<String,Object> user = userManage.findUserMapByUsername( username );
	    	model.put("data", user );
	    	
	    	RoleGroup mo = new RoleGroup();
	    	mo.setS_username(user.get("username").toString());
	    	List<Map<String,Object>> groups = roleGroupManage.findRoleGroupMapsByCond(mo , -1, -1);
	    	String groupsStr = "";
	    	for (Map<String, Object> g : groups) {
	    		groupsStr = groupsStr + g.get("gid").toString() + "," ;
			}
	        model.put("groupsStr", groupsStr);
	        
        }catch(AccessDeniedException e) {
        	e.printStackTrace();
		}catch (Exception e) {
			e.printStackTrace();
		}
        return "/sysmanage/user/template/user_assignrole";
    }
    
    /**
     * 保存分配角色页面
     * @param username
     * @return
     */
    @RequestMapping( value={"/user/user_assignRole"} )
    @ResponseBody
    public Map<String,Object> assignUser( 
    		@RequestParam(value="username") String username, 
    		@RequestParam(value="roleIds", required=false ) String ids,  
    		ModelMap model  ){
    	roleGroupManage.removeUserFromAllGroup(username);
    	String[] idArr = ids.split(",");
    	for (String id : idArr) {
    		roleGroupManage.addUserToGroupById(username, id);
		}
        return model;
    }
    
    /**
     * 删除用户
     * @param username
     * @param ids
     * @param model
     * @return
     */
    @RequestMapping( value={"/user/user_delete"} )
    @ResponseBody
    public Map<String,Object> deleteUser( 
    		@RequestParam(value="username") String username, 
    		ModelMap model  ){
    	int res = userManage.deleteUserByUsername(username);
    	model.put("res", res );
    	return model;
    }
    //-------------------------------------------------------------------角色组管理----------------------------------------------------------------------------------------
    /**
     * 获取角色组管理列表
     * @return
     */
    @RequestMapping(value = { "/rolegroup/rolegrouplist" }   )
    public String rolegrouplist( HttpServletRequest request, ModelMap model) {
    	String pjax = request.getHeader("X-PJAX") ;
    	
    	if( StringUtils.isBlank(pjax)){
    		return "/sysmanage/rolegroup/rolegroup_index_whole";
    	}
    	return "/sysmanage/rolegroup/rolegroup_index";
    }
    
    /**
     * 返回角色组列表json数据， 支持easyui datagrid控件
     * @param model
     * @return
     */
    @ResponseBody
    @RequestMapping(value = { "/rolegroup/rolegroup_datagrid/json" }   )
    public Map<String,Object> rolegroupIndex( @RequestParam(value="page",required=false) int page, 
            @RequestParam(value="pageSize",required=false) int pageSize,
            ModelMap model) {
        Map<String,Object> datagridMap = new HashMap<String,Object>();
        try {
            RoleGroup mo = new RoleGroup();
            List<Map<String,Object>> list = roleGroupManage.findRoleGroupMapsByCond(mo, -1,  -1);
//            int count = roleGroupManage.findRoleGroupCountByCond(mo);
            int count = list.size();
            datagridMap.put("total", count);
            datagridMap.put("rows", list);
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        return datagridMap;
    }
    
    /**
     * 返回角色组列表json数据， 支持easyui tree 控件
     * @param model
     * @return
     */     
    @ResponseBody
    @RequestMapping(value = { "/rolegroup/rolegroup_tree/json" }   )
    public Map<String,Object> rolegroupTree( @RequestParam(value="index") String index, 
            ModelMap model) {
        Map<String,Object> datagridMap = new HashMap<String,Object>();
        try {
            RoleGroup mo = new RoleGroup();
            List<Map<String,Object>> list = roleGroupManage.findRoleGroupMapsByCond(mo, -1,  -1);
//            int count = roleGroupManage.findRoleGroupCountByCond(mo);
            List<ETree> trees = new ArrayList<ETree>();
            for (Map<String, Object> map : list) {
            	ETree t = new ETree();
            	t.setId( map.get("id").toString() );
            	t.setText( map.get("group_name").toString() );
            	trees.add(t);
			}
            ETree t = new ETree();
            t.setId("-1");
            t.setText("角色列表");
            t.setChildren( trees.toArray( new ETree[trees.size()]) );
            
            List<ETree> returnlist = new ArrayList<ETree>();
            returnlist.add(t);
            datagridMap.put("rows", returnlist );
            model.put("index", index);
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        return datagridMap;
    }
    
    /**
     * 打开角色组编辑页面
     * @return
     */
    @RequestMapping(value = { "/rolegroup/preSaveRolegroup" }   )
    public String preSaveRolegroup( 
		 @RequestParam(value="rolegroup_name") String rolegroup_name,  
		 @RequestParam(value="index") String index,  
            ModelMap model) {
    	Map<String, Object> data = roleGroupManage.findRoleGroupMapByName(rolegroup_name);
    	model.put("data", data);
        model.put("index", index);
        return "/sysmanage/rolegroup/rolegroup_edit";
    }
    
    /**
     * 修改角色组
     * @return
     */
    @RequestMapping(value = { "/rolegroup/saveRolegroup" }   )
    @ResponseBody
    public Map<String,Object> saveRolegroup( 
    		@RequestParam(value="id") String id,
    		@RequestParam(value="rolegroup_name") String rolegroup_name,  
    		ModelMap model) {
    	try {
        	RoleGroup mo = new RoleGroup();
        	mo.setGroupname(rolegroup_name);
        	mo.setId(id);
        	
        	Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        	if( principal instanceof User ){
        		User u =(User)principal;
        		System.out.println( u.getAuthorities() );
        	}
        	
    		int data = roleGroupManage.modifyRoleGroup(mo);
        	model.put("res", data);
		}catch (AccessDeniedException e) {
			//e.printStackTrace();
			model.put("res", -2 );
		} catch (Exception e) {
			e.printStackTrace();
		}
        return model ;
    }
    
    /**
     * 打开授权页面
     * @return
     */
    @RequestMapping(value = { "/permission/permissionList" }   )
    public String permissionlist( 
		 @RequestParam(value="rolegroup_id") String groupId,  
		 @RequestParam(value="index") String index,  
            ModelMap model) {
    	String ps = roleGroupManage.findRolegroupPermission(groupId);
    	model.put("ps", ps);
    	Permission mo = new Permission();
        List<Permission> list = getAllPermission( mo );
        model.put("rolegroup_id", groupId );
        model.put("list", list);
        model.put("index", index);
        return "/sysmanage/permission/permission";
    }
    
    private List<Permission> getAllPermission( Permission mo ){
        List<Permission> list = permissionDao.findPermissionsByCond( mo , -1, -1);
        for (Permission pm : list) {
            Permission tmp = new Permission();
            tmp.setParent_uuid( pm.getUuid() );
            pm.setChildren(  getAllPermission(  tmp ) );
        }
        return list;
    }
    
    /**
     * 保存授权结果
     */
    @ResponseBody
    @RequestMapping(value = { "/permission/save" }   )
    public Map<String,Object> permissionSave( 
    		@RequestParam(value="permission_keys") String[] permission_keys, 
    		@RequestParam(value="rolegroup_id") String rolegroup_id,  
            ModelMap model ) {
    	Map<String,Object> map = new HashMap<String,Object>();
    	try {
        	int t = roleGroupManage.assignRolegroupPermission( rolegroup_id, permission_keys );
        	map.put("res", t);
		} catch (Exception e) {
			e.printStackTrace();
		}
        return map ;    	
    }
    
 
    
}
